package lk.week02;

import commons.ListNode;

/**
 * ClassName: P0002_AddTwoNumbers
 * Description:
 * Author: xyf
 * Date: 5/21/23 9:41 AM
 * Version: 1.0
 **/
public class P0002_AddTwoNumbers
{
    public ListNode addTwoNumbers(ListNode l1, ListNode l2)
    {
        ListNode head = null;
        ListNode tail = null;
        int last = 0;
        while (l1 != null || l2 != null)
        {
            int sum = 0;
            if (l1 != null)
            {
                sum += l1.val;
            }
            if (l2 != null)
            {
                sum += l2.val;
            }
            sum += last;
            last = sum / 10;
            int num = sum % 10;
            ListNode cur = new ListNode(num);
            if (head == null)
            {
                head = cur;
                tail = cur;
            }
            else
            {
                tail.next = cur;
                tail = tail.next;
            }

            if (l1 != null)
            {
                l1 = l1.next;
            }
            if (l2 != null)
            {
                l2 = l2.next;
            }
        }
        if (last > 0)
        {
            ListNode cur = new ListNode(last);
            tail.next = cur;
        }
        return head;
    }

}